package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import view.NewMeetingView;
import view.ViewHelpers;
import model.AppModel;
import model.Email;
import model.EmailBuilder;
import model.Meeting;
import model.ModelException;

/**
 * This class controls the  New Meeting View
 * 
 * Controller assigns events of sending and saving a new meeting 
 * and specifies the actions to invoke upon triggering these events. 
 * @author buthainahaldosary
 * @since May 31, 2013
 *
 * @version $Revision: 1.0 $
 */
public class NewMeetingController {
	
		/**
		 *  Application model, view and main contrlller
		 */
		private AppModel model;
		/**
		 * New meeting to create
		 */
		private Meeting meeting;
		
		/**
		 *  The view to work on
		 */
		private NewMeetingView view;
		/**
		 * Constructor 
		 * @param model the current model to work on
		 * @param meeting Meeting
		 */
	public NewMeetingController(AppModel model,Meeting meeting) {
		this.model = model; 
		view = new NewMeetingView();
		
		assignHandlersToEvents();
		refreshView();
		view.showDialog();
	}
	/**
	 * Method to register and assign handlers to events
	 */
	private void assignHandlersToEvents() {
		//send

				view.getCreateBtn().addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						actionCreateNewMeeting();
					}
				});
				
				//cancel
				view.getCancelBtn().addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						actionCancel();
					}
				});
	}
	
	/**
	 * Method that is triggered when the cancel button is clicked.
	 */
	protected void actionCancel() {
		ViewHelpers.disposeParentDialog(view.getPanel());
		
	}
	/**
	 * Method that is triggered when the send button is clicked
	 */
	@SuppressWarnings("null")
	protected void actionCreateNewMeeting() {
		// Sanitize user input
		String newTopic = view.getTopicText().toLowerCase().trim();
		String newLocation = view.getLocationText().toLowerCase().trim();
		//handle string inputs here
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy.mm.dd hh:mm");
		String newStart = view.getStartDateText().toLowerCase().trim();
		String newEnd=view.getEndDateText().toLowerCase().trim();
		Date parsedStartDate=null;
		Date parsedEndDate=null;
		Timestamp startDate = null;
		Timestamp endDate=null;
		
		Meeting tempMeeting = null;
		//tempMeeting=new Meeting(-1, "topic", "location", startDate, endDate, "attendees", "Description");
		try {
			parsedStartDate = sdf.parse(newStart);
			parsedEndDate = sdf.parse(newEnd);
			 startDate=new Timestamp(parsedStartDate.getTime());
			 endDate=new Timestamp(parsedEndDate.getTime());
			 	//tempMeeting.setEnd(endDate);
				//tempMeeting.setStart(startDate);
		} catch (ParseException e1) {
			ViewHelpers.alertError("Please make sure you entered valid inputs for the dates");
			return;
		}
		
		
		String newAttendees=view.getAttendeesText().toLowerCase().trim();
		String newDescription=view.getDescriptionText().toLowerCase().trim();
		
		// validate input
		if (!areValidInputs(newTopic, newLocation,newStart,newEnd,newAttendees,newDescription,tempMeeting)){
			return;
		}
		Meeting meeting;
		
		try {
			// Create the meeting
			meeting=model.getUser().createNewMeeting(newTopic, newLocation, startDate, endDate, newAttendees, newDescription);
			//sent emails to reciepients
			//String recipientList=meeting.getAttendees();
			// extract each recipient
			//List<String> recipients = Arrays.asList(recipientList.split(","));
			//create email for each recipient
			String body="";
			java.util.Date date= new java.util.Date();
			 Timestamp currentTime = new Timestamp(date.getTime());
			//for (String recipient : recipients)
			//{
				//recipient=recipient.trim();
				body="Hello "+meeting.getAttendees()+"\n A meeting was created (or updated) by "+model.getUser().getName()+" which includes you. Here are the details:\n"+
			"Start time: "+meeting.getStart().toGMTString()+"\n "+
						"End time: "+ meeting.getEnd().toGMTString()+"\n"+
			"Topic: " +meeting.getTopic()+"\n Description: "+ meeting.getDescription()+"\n Other attendees: "+ meeting.getAttendees()+"\n Thank you.";
			int folderId= model.getUser().getFolder("Outbox").getId();			
			//Email emailToSend =  new EmailBuilder().setFrom(model.getUser().getName()).setTo(meeting.getAttendees()).setSubject(newTopic).setRead(false).setBody(body).setFolderId(folderId).build();
			//emailToSend.save();
			//model.getUser().getFolder("Outbox").getEmails().add(emailToSend);
			
			
			//Send email to server
			
			//Result of meeting creation from the server
			//Meeting createdMeeting=
			//createdMeeting.save();
			
			
			
			
			
			ViewHelpers.disposeParentDialog(view.getPanel());
		//}
		}catch (ModelException e) {
			ViewHelpers.alertError("Problem creating meeting.");
			return;
		}
		
		
		
	}
	
	/**
	 * Refresh view sets all the field's texts to be empty.
	 */
	private void refreshView() {
		
		view.getAttendees().setText("");
		view.getDescription().setText("");
		
		Timestamp start=new Timestamp(new java.util.Date().getTime());
		Timestamp end=new Timestamp(new java.util.Date().getTime());
		
		
		
		
		String S = new SimpleDateFormat("yyyy.mm.dd hh:mm").format(start);
		String E = new SimpleDateFormat("yyyy.mm.dd hh:mm").format(end);
		
		
		
		view.getStartDate().setText(S);
		view.getEndDate().setText(E);
		
		
		
		
		
		view.getLocation().setText("");
		view.getTopic().setText("");
		
	}
	/**
	 * This method validated the meeting input for fields by checking if they are empty or not
	 * @param topic : user input for meeting topic
	 * @param tempMeeting 
	
	
	
	
	
	
	 * @param location String
	 * @param start String
	 * @param end String
	 * @param attendees String
	 * @param description String
	 * @return boolean value indicating that the inputs are valid or not. */
	private Boolean areValidInputs(String topic, String location,String start, String end, String attendees, String description, Meeting tempMeeting){
		
		// Empty strings
		if (topic.isEmpty() || location.isEmpty()|| start.isEmpty() || end.isEmpty()||attendees.isEmpty()||description.isEmpty()){
			ViewHelpers.alertError("Please make sure all fields are not empty");
			return false;
		}
		// start > end date
		if(!isCorrectDates(start,end))
		{
			ViewHelpers.alertError("Please make sure start date is before end date");
			return false;
		}
		
		//check if meetings overlap
//		if(model.getUser().checkIfDatesOverlap(tempMeeting))
//		{
//			ViewHelpers.alertError("You already have a meeting that overlaps with the specified dates. Please enter new values.");
//			return false;
//		}
		// If a new meeting, check for existing topic
		if (meeting == null){
			for (Meeting meeting : model.getUser().getMeetings()){
				if (meeting.getTopic().trim().equalsIgnoreCase(topic)){
					ViewHelpers.alertError("You already have a meeting with the same topic, please use a different one");
					return false;
				}
			}
		}
				
			
		return true;
				
	}
	/**
	 * Method isCorrectDates.
	 * @param start String
	 * @param end String
	 * @return boolean
	 */
	private boolean isCorrectDates(String start, String end) {
		//handle string inputs here
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy.mm.dd hh:mm");
		Date parsedStartDate=null;
		Date parsedEndDate=null;
		Timestamp startDate = null;
		Timestamp endDate=null;
		try {
			parsedStartDate = sdf.parse(start);
			parsedEndDate = sdf.parse(end);
			 startDate=new Timestamp(parsedStartDate.getTime());
			 endDate=new Timestamp(parsedEndDate.getTime());
		} catch (ParseException e1) {
			ViewHelpers.alertError("Please make sure you entered valid inputs for the dates");
			return false;
			
		}
		if(startDate.after(endDate))
		return false;
		else
			return true;
	}


}
